package cn.fl.project.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.constant.CapCashDepositDeductionConstant;
import cn.fl.capital.constant.SettleConstant;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjPrdPaySchBankQueryCondition;
import cn.fl.project.constant.PrjPrdPaySchBankConstant;
import cn.fl.project.constant.PrjQuatPrpsConstant;
import cn.fl.project.dto.PrjPrdPaySchBankDTO;
import cn.fl.project.service.IPrjPrdPaySchBankService;
import cn.fl.project.vo.PrjPrdPaySchBankVO;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 支付表结清账号记录表 控制层
 */
@Controller
@RequestMapping("/project/prjPrdPaySchBank")
public class PrjPrdPaySchBankController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(PrjPrdPaySchBankController.class);

	/**
	 * PrjPrdPaySchBank 服务层BEAN
	 */
	@Autowired
	private IPrjPrdPaySchBankService prjPrdPaySchBankService;

   /* @Autowired
    private  IPrjBindComMoneyService  prjBindComMoneyService;*/

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("project/prjPrdPaySchBank/list");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("project/prjPrdPaySchBank/prjPrdPaySchBankAdd");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toAddPage", "跳转到新增/修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到新增或修改结清账户信息页面  dialog
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/toAddDialogPage.do", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView toAddDialogPage(HttpServletRequest request) {
		String id = request.getParameter("id");
		String paySchId = request.getParameter("paySchId");
		String insCode = request.getParameter("insCode");
		String paySchDId = request.getParameter("paySchDId");
		// 1-客户付款账户  2-客户收款账户  3-我司付款账户  4-我司收款账户 5-保证金抵扣我司收款账户
		String bindType = request.getParameter("bindType");
		ModelAndView view = new ModelAndView("project/prjPrdPaySchBank/paySchBankAdd");
		view.addObject("insCode", insCode);
		PrjPrdPaySchBankDTO bankDTO = new PrjPrdPaySchBankDTO();
		if (StringUtils.isNotEmpty(id)) {
			bankDTO = prjPrdPaySchBankService.selectById(Long.parseLong(id));
		}
		if (bankDTO.getId() == null && "3".equals(bindType)) {
			bankDTO.setBankNm(SettleConstant.REFUND_BANK_NAME_ALL);
			bankDTO.setAccNo(SettleConstant.REFUND_BANK_ACCOUNT);
		}
		view.addObject("bank", bankDTO);
		view.addObject("paySchId", paySchId);
		view.addObject("bindType", bindType);
		view.addObject("paySchDId", paySchDId);
		BaseLogUtils.info(logger, "toAddDialogPage", "跳转到新增或修改结清账户信息页面.paySchId=" + paySchId + "，id=" + id, CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String paySchId = request.getParameter("paySchId");
		String paySchDId = request.getParameter("paySchDId");
		String fundFlowCd = request.getParameter("fundFlowCd");
		String fundTypCd = request.getParameter("fundTypCd");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		PrjPrdPaySchBankQueryCondition qc = new PrjPrdPaySchBankQueryCondition();
		if (StringUtils.isNotEmpty(paySchId)) {
			qc.setPaySchId(Long.valueOf(paySchId));
		}
		if(StringUtils.isNotEmpty(fundTypCd)){
			qc.setFundTypCd(fundTypCd);
		}
		if(StringUtils.isNotEmpty(fundFlowCd)){
			qc.setFundFlowCd(fundFlowCd);
		}
		if (StringUtils.isNotEmpty(paySchDId)) {
			qc.setPaySchDId(Long.valueOf(paySchDId));
		}
		page.setCondition(qc);

		Pager pager = this.prjPrdPaySchBankService.searchListPage(page);
		List<PrjPrdPaySchBankVO> list = (List<PrjPrdPaySchBankVO>) pager.getResultList();
		ListPageVO<PrjPrdPaySchBankVO> listPage = new ListPageVO<PrjPrdPaySchBankVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}


    /**
     * 初始化绑定来款页面列表
     */
    /*@SuppressWarnings("unchecked")
    @RequestMapping(value = "/initComMoneyList.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object initComMoneyList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String paySchId = request.getParameter("paySchId");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        PrjBindComMoneyQC qc = new PrjBindComMoneyQC();
        if (StringUtils.isNotEmpty(paySchId)) {
            qc.setPaySchId(Long.valueOf(paySchId));
        }
        page.setCondition(qc);

        Pager pager = this.prjBindComMoneyService.searchListPage(page);
        List<PrjBindComMoneyVO> list = (List<PrjBindComMoneyVO>) pager.getResultList();
        ListPageVO<PrjBindComMoneyVO> listPage = new ListPageVO<PrjBindComMoneyVO>(list, pager.getTotalCount());
        BaseLogUtils.info(logger, "initComMoneyList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        return listPage;
    }*/


    /**
     *  to绑定来款选择页面列表
     */
    /*@SuppressWarnings("unchecked")
    @RequestMapping(value = "/toBindComMoneySelectPage.do", method = { RequestMethod.GET})
    @ResponseBody
    public ModelAndView toBindComMoneySelectPage(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("project/prjPrdPaySchBank/prjPrdPayBindComMoneyAdd");
        BaseLogUtils.info(logger, "toBindComMoneySelectPage", "跳转到新增选择页面", CurrentThreadContext.getCurrentUserName());
        return view;
    }*/



	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(ids)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "removePrdById", "删除数据,主键参数为空！", CurrentThreadContext.getCurrentUserName());
			return result;
		}

		List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.fromObject(ids);
		for (Object object : idsArray) {
			idsList.add(Long.valueOf(object.toString()));
		}
		try {
			boolean success = this.prjPrdPaySchBankService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removePrdById", "删除产品数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeByIds", "删除数据.[ids="+ids+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeByIds", "删除数据失败.[ids="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeByIds", "删除数据失败.[ids="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 批量保存
	 */
	@RequestMapping(value = "/batchAdd.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object batchAdd(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		List<PrjPrdPaySchBankVO> VOList = new ArrayList<PrjPrdPaySchBankVO>();
        /*List<PrjBindComMoneyVO> prjBindComMoneyVoList = new ArrayList<PrjBindComMoneyVO>();*/

		try {
			VOList = this.getRequestParamForAdd(request);
            /*prjBindComMoneyVoList= this.getRequestBindComMoneyParam(request);*/
			boolean success = this.prjPrdPaySchBankService.batchAdd(VOList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "batchAdd", "批量保存失败,VOList:"+JSON.toJSONString(VOList), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "batchAdd", "批量保存.[VOList="+JSON.toJSONString(VOList)+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "batchAdd", "批量保存失败.DATA:" + JSONObject.toJSONString(VOList) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "batchAdd", "批量保存失败.DATA:" + JSONObject.toJSONString(VOList) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	//********************私有方法********************//
	/**
	 * 获取参数信息
	 * @param request
	 * @return
	 * @throws BaseException
	 */
	private List<PrjPrdPaySchBankVO> getRequestParam(HttpServletRequest request)throws BaseException{
		String paySchId = request.getParameter("paySchId");//支付表ID
		String bindType = request.getParameter("bindType");
		//支付表租金明细ID，保证抵扣流程DATA_ID
		String paySchDId = request.getParameter("paySchDId");

		if(StringUtils.isEmpty(paySchId)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "支付表ID不能为空.");
		}
		List<PrjPrdPaySchBankVO> prjPrdPaySchBankVOList = new ArrayList<PrjPrdPaySchBankVO>();
		/**资金流入  我司收款*/
		//客户付款账户
		String cstBankJSON = request.getParameter("cstBankJSON");
		if (StringUtils.isNotEmpty(cstBankJSON)) {
			List<PrjPrdPaySchBankVO> cstBankJSONList = JSON.parseArray(cstBankJSON, PrjPrdPaySchBankVO.class);
			if (CollectionUtils.isNotEmpty(cstBankJSONList)) {
				for (PrjPrdPaySchBankVO prjPrdPaySchBankVO : cstBankJSONList) {
					prjPrdPaySchBankVO.setFundFlowCd(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CASH_FLOW_IN);//资金流入
					prjPrdPaySchBankVO.setFundTypCd(PrjPrdPaySchBankConstant.CODE_PAY_SCH_FUND_TYP_CD_OUT);//付款账户
					prjPrdPaySchBankVO.setPaySchId(Long.valueOf(paySchId));
					if (null != prjPrdPaySchBankVO.getPayAmtDouble()) {
						prjPrdPaySchBankVO.setPayAmt(DecimalUtils.convertYuanToFen(prjPrdPaySchBankVO.getPayAmtDouble()));//金额元转分
					}
				}
				prjPrdPaySchBankVOList.addAll(cstBankJSONList);
			}
		}
		//我司收款账户
		String ourComBankJSON = request.getParameter("ourComBankJSON");
		if (StringUtils.isNotEmpty(ourComBankJSON)) {
			List<PrjPrdPaySchBankVO> ourComBankList = JSON.parseArray(ourComBankJSON, PrjPrdPaySchBankVO.class);
			if (CollectionUtils.isNotEmpty(ourComBankList)) {
				for (PrjPrdPaySchBankVO prjPrdPaySchBankVO : ourComBankList) {
					prjPrdPaySchBankVO.setFundFlowCd(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CASH_FLOW_IN);//资金流入
					prjPrdPaySchBankVO.setFundTypCd(PrjPrdPaySchBankConstant.CODE_PAY_SCH_FUND_TYP_CD_INTO);//收款账户
					prjPrdPaySchBankVO.setPaySchId(Long.valueOf(paySchId));
					if (null != prjPrdPaySchBankVO.getPayAmtDouble()) {
						prjPrdPaySchBankVO.setPayAmt(DecimalUtils.convertYuanToFen(prjPrdPaySchBankVO.getPayAmtDouble()));//金额元转分
					}
				}
				prjPrdPaySchBankVOList.addAll(ourComBankList);
			}
		}
		/**资金流出  我司付款*/
		//客户收款账户
		String cstBankJSON_1 = request.getParameter("cstBankJSON_1");
		if (StringUtils.isNotEmpty(cstBankJSON_1)) {
			List<PrjPrdPaySchBankVO> cstBankJSONList_1 = JSON.parseArray(cstBankJSON_1, PrjPrdPaySchBankVO.class);
			if (CollectionUtils.isNotEmpty(cstBankJSONList_1)) {
				for (PrjPrdPaySchBankVO prjPrdPaySchBankVO : cstBankJSONList_1) {
					if(!"5".equals(bindType)){
						prjPrdPaySchBankVO.setFundFlowCd(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT);//资金流出
						prjPrdPaySchBankVO.setFundTypCd(PrjPrdPaySchBankConstant.CODE_PAY_SCH_FUND_TYP_CD_INTO);//收款账户
					}else{
						//保证金抵扣增加用户收款账户信息
						prjPrdPaySchBankVO.setFundFlowCd(CapCashDepositDeductionConstant.FUND_FLOW_INTO);//资金流入
						prjPrdPaySchBankVO.setFundTypCd(CapCashDepositDeductionConstant.FUND_TYP_CST);//收款账户
						if(StringUtils.isEmpty(paySchDId)){
							throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "保证金抵扣添加用户收款信息账户信息,支付表明细ID不能为空.");
						}else{
							prjPrdPaySchBankVO.setPaySchDId(Long.valueOf(paySchDId));
						}
					}
					prjPrdPaySchBankVO.setPaySchId(Long.valueOf(paySchId));
					if (null != prjPrdPaySchBankVO.getPayAmtDouble()) {
						prjPrdPaySchBankVO.setPayAmt(DecimalUtils.convertYuanToFen(prjPrdPaySchBankVO.getPayAmtDouble()));//金额元转分
					}
				}
				prjPrdPaySchBankVOList.addAll(cstBankJSONList_1);
			}
		}
		//我司付款账户
		String ourComBankJSON_1 = request.getParameter("ourComBankJSON_1");
		if (StringUtils.isNotEmpty(ourComBankJSON_1)) {
			List<PrjPrdPaySchBankVO> ourComBankList_1 = JSON.parseArray(ourComBankJSON_1, PrjPrdPaySchBankVO.class);
			if (CollectionUtils.isNotEmpty(ourComBankList_1)) {
				for (PrjPrdPaySchBankVO prjPrdPaySchBankVO : ourComBankList_1) {
					prjPrdPaySchBankVO.setFundFlowCd(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT);//资金流出
					prjPrdPaySchBankVO.setFundTypCd(PrjPrdPaySchBankConstant.CODE_PAY_SCH_FUND_TYP_CD_OUT);//付款账户
					prjPrdPaySchBankVO.setPaySchId(Long.valueOf(paySchId));
					if (null != prjPrdPaySchBankVO.getPayAmtDouble()) {
						prjPrdPaySchBankVO.setPayAmt(DecimalUtils.convertYuanToFen(prjPrdPaySchBankVO.getPayAmtDouble()));//金额元转分
					}
				}
				prjPrdPaySchBankVOList.addAll(ourComBankList_1);
			}
		}
		if(CollectionUtils.isEmpty(prjPrdPaySchBankVOList)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "没有要保存的账户信息.");
		}
		return prjPrdPaySchBankVOList;
	}

    /*private List<PrjBindComMoneyVO> getRequestBindComMoneyParam(HttpServletRequest request)throws BaseException{

        List<PrjBindComMoneyVO> prjBindComMoneyVoList = new ArrayList<PrjBindComMoneyVO>();
        String paySchId = request.getParameter("paySchId");//支付表ID
        if(StringUtils.isEmpty(paySchId)){
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "支付表ID不能为空.");
        }
        *//**资金流入  我司收款*//*
        //客户付款账户
        String bindComeJSON = request.getParameter("bindComeMoneyJSON");
        List<PrjBindComMoneyVO> cstBankJSONList = new ArrayList<PrjBindComMoneyVO>();
        if(null!=bindComeJSON) {
            prjBindComMoneyVoList = JSON.parseArray(bindComeJSON, PrjBindComMoneyVO.class);
            Long paySchIdValue=Long.parseLong(paySchId);
            for(PrjBindComMoneyVO vo:prjBindComMoneyVoList){
                if(vo.getPaySchId()==null){
                    vo.setPaySchId(paySchIdValue);
                }
            }
        }
        return prjBindComMoneyVoList;
    }*/


	/**
	 * 获取请求参数(新增)
	 * @param request 请求
	 * @return
	 */
	private List<PrjPrdPaySchBankVO> getRequestParamForAdd(HttpServletRequest request)throws BaseException{
		List<PrjPrdPaySchBankVO> prjPrdPaySchBankVOList = this.getRequestParam(request);
		if(CollectionUtils.isNotEmpty(prjPrdPaySchBankVOList)){
			for (PrjPrdPaySchBankVO prjPrdPaySchBankVO : prjPrdPaySchBankVOList) {
				if(prjPrdPaySchBankVO.getId()!=null){//修改
					prjPrdPaySchBankVO.setMdfTm(new Date());
					prjPrdPaySchBankVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				}else{//新增
					prjPrdPaySchBankVO.setCrtTm(new Date());
					prjPrdPaySchBankVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				}
			}
		}
		return prjPrdPaySchBankVOList;
	}



}

